<template>
  <div class="form-fragment">
    <div class="form-container" v-if="dynamicForm.length">
      <tbc-dynamic-form :form="dynamicForm" class="compact"/>
    </div>

    <div class="form-container" v-if="!dynamicForm.length">
      <div
          style="height: 100px;line-height: 100px;padding-left:20px;width: 100%;border-radius: 10px;border:1px solid #CCC">
        <span style="font-size: 24px">分类未关联任何商品模型或关联的商品模型未设置基础属性</span>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import {defineComponent, reactive, toRefs} from 'vue'

export default defineComponent({
  name: 'goods-form-attribute',

  setup() {

    const state = reactive({
      attribute: [],
      fillData: [],
      dynamicForm: []
    })

    const init = (data: any) => {
      if (typeof data === 'undefined') return;
      state.fillData = data
      initDynamicForm()
    }

    const initDynamicForm = () => {
      if (!state.dynamicForm.length || !state.fillData.length) return
      state.dynamicForm.forEach((item: Record<string, string>) => {
        state.fillData.forEach((attr: any) => {
          if (item.field === attr.attr_id) {
            let value = attr.value
            if (['checkbox'].indexOf(item.type) === -1) value = value.join('');
            item.value = value
          }
        })
      })
    }

    const setDynamicForm = (data: any) => {
      state.attribute = data
      buildDynamicAttrForm()
    }

    const buildDynamicAttrForm = () => {
      const dynamicForm: { [k: string]: any }[] = []
      state.attribute.forEach((attr: any) => {
        let item: Record<string, any> = {};
        item.label = attr.attr_name
        item.type = attr.input_type
        item.field = attr.attr_id
        item.options = attr.attr_values
        item.value = ''
        if (['checkbox'].indexOf(item.type) > -1) item.value = []
        dynamicForm.push((item))
      });
      (state.dynamicForm as { [k: string]: any }[]) = dynamicForm
      initDynamicForm()
    }

    const getFormData = () => {
      console.log('getFormData')
      // let attr = [];
      // dynamicForm.value.forEach(item => attr.push({id: item.field, value: item.value}))
      // return JSON.stringify(attr);
    }

    return {
      ...toRefs(state),
      init,
      setDynamicForm,
      getFormData
    }
  }
})
</script>